<template>
  <div class="post-detail-page">
    <modal
      title="删除文章"
      :visible="modalIsVidible"
      @modal-on-close="modalIsVidible = false"
      @modal-on-confirm="hideAndDelete"
    >
      <p>确定要删除这篇文章？</p>
    </modal>
    <article class="w-75 mx-auto mb-5 pb-3" v-if="currentPost">
      <!-- 文章如果有图的话展示图 -->
      <img
        :src="currentImageUrl"
        alt="currentPost.title"
        class="rounded-lg img-fluid my-4"
        v-if="currentImageUrl"
      />
      <!-- 展示标题 -->
      <h2 class="mb-4">{{ currentPost.title }}</h2>
      <!-- 左边是作者的信息userpofile 右边是发表时间 -->
      <div
        class="user-profile-component border-top border-bottom py-3 mb-5 align-items-center row g-0"
      >
        <div class="col">
          <user-profile
            :user="currentPost.author"
            v-if="typeof currentPost.author === 'object'"
          ></user-profile>
        </div>
        <span class="text-muted col text-right font-italic"
          >发表于：{{ currentPost.createdAt }}</span
        >
      </div>
      <!-- 文章内容 -->
      <!-- 这里展示文章的具体内容 需要将markdown格式的进行转换 -->
      <div v-html="currentHTML"></div>
      <div v-if="showEditArea" class="btn-group mt-5">
        <router-link
          type="button"
          class="btn btn-success"
          :to="{ name: 'createPost', query: { id: currentPost._id } }"
        >
          编辑
        </router-link>
        <button
          type="button"
          class="btn btn-danger"
          @click.prevent="modalIsVidible = true"
        >
          删除
        </button>
      </div>
    </article>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router"; // 路由 useRoute是获取路由的信息
import { useStore } from "vuex";
import { PostProps, ImageProps, UserProps, ResponseType } from "@/store";
// import MarkdownIt from "markdown-it"; 这里修改为和easymde一样的marked编辑结果
import { marked } from "marked";
import UserProfile from "../components/UserProfile.vue";
import Modal from "../components/Modal.vue";
import createMessage from "../components/createMessage";

export default defineComponent({
  name: "post-detail",
  components: {
    UserProfile,
    Modal
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    const currentId = route.params.id;
    // const md = new MarkdownIt(); // 解析markdown语法的插件的使用
    const modalIsVidible = ref(false);
    onMounted(() => {
      store.dispatch("fetchPost", currentId);
    });
    // console.log(store.state.posts);
    // const post = store.getters.getCurrentPost(currentId)
    // -> 拿文章的类来约束post
    // computed是函数的形式 这里返回值需要被约束
    const currentPost = computed<PostProps>(() => {
      return store.getters.getCurrentPost(currentId);
    });
    // 拿到文章详情之后 要剥离出来 图
    const currentImageUrl = computed(() => {
      if (currentPost.value && currentPost.value.image) {
        const { image } = currentPost.value;
        return (image as ImageProps).url + "?x-oss-process=image/resize,w_850";
      } else {
        return null;
      }
    });
    // 取出文章详情信息 将文章的markdown格式内容解析成html格式
    const currentHTML = computed(() => {
      // md.render(文章内容)
      if (currentPost.value && currentPost.value.content) {
        // return md.render(currentPost.value.content);
        const { isHTML, content } = currentPost.value;
        return isHTML ? content : marked.parse(content); // 改成新的marked
      }
      return null;
    });
    // 添加文章编辑功能 当当前用户和文章author是同一个人的时候 显示可删除、编辑的按钮
    const showEditArea = computed(() => {
      const { isLogin, _id } = store.state.user;
      if (currentPost.value && currentPost.value.author && isLogin) {
        // 现在author是联合类型（string | UserProps | undefined） 但是我们知道是UserProps对象
        // 可以做一下类型断言
        const postAuthor = currentPost.value.author as UserProps;
        return postAuthor._id === _id;
      }
      return false;
    });
    // 删除文章功能
    const hideAndDelete = () => {
      modalIsVidible.value = false;
      store
        .dispatch("deletePost", currentId)
        .then((rawData: ResponseType<PostProps>) => {
          createMessage("删除成功", "success", 2000, "跳转到专栏首页");
          // createMessage("删除成功，2秒后跳转到专栏首页", "success", 2000);
          setTimeout(() => {
            router.push({
              name: "column",
              params: {
                id: rawData.data.column
              }
            });
          }, 2000);
        });
    };
    return {
      currentPost,
      currentImageUrl,
      currentHTML,
      showEditArea,
      modalIsVidible,
      hideAndDelete
    };
  }
});
</script>
